package com.pig.graduate.controller.sys;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig.graduate.common.constant.Constant;
import com.pig.graduate.domain.sys.*;
import com.pig.graduate.result.MyResult;
import com.pig.graduate.service.sys.SysBuildingsService;
import com.pig.graduate.service.sys.SysColumnService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.security.Principal;
import java.util.*;

@Api(tags = {"猪栏管理"}, description = "猪栏管理")
@RestController
@RequestMapping("/sys/column")
public class SysColumnController {

    @Autowired
    private SysColumnService sysColumnService;

    @Autowired
    private SysBuildingsService sysBuildingsService;

    /**
     * 根据栋舍查找猪栏
     * @param buildingsId
     * @return
     */
    @ApiOperation(value = "猪栏列表",notes = "猪栏列表")
    @GetMapping("/getColumnByBuildingsId")
    public MyResult getColumnByBuildingsId(@RequestParam("buildingsId") Integer buildingsId){
        List<SysColumn> sysColumnList = sysColumnService.list(new QueryWrapper<SysColumn>().eq("buildings_id",buildingsId));
        return MyResult.success(sysColumnList);
    }

    /**
     * 添加或者修改
     * @param sysColumn
     * @return
     */
    @ApiOperation(value = "添加或者修改",notes = "添加或者修改")
    @PostMapping("/saveAndUpdate")
    public MyResult saveAndUpdate(@RequestBody @Valid SysColumn sysColumn){
        if(sysColumn.getId()==null || sysColumn.getId()==0){
            sysColumn.setCreateTime(new Date());
            sysColumnService.save(sysColumn);
            SysBuildings sysBuildings = sysBuildingsService.getById(sysColumn.getBuildingsId());
            sysBuildings.setSumColumnNumber(sysBuildings.getSumColumnNumber()+1);
            sysBuildingsService.updateById(sysBuildings);
        }else{
            sysColumn.setUpdateTime(new Date());
            sysColumnService.updateById(sysColumn);
        }
        return MyResult.success();
    }



    /**
     * 删除
     * @param ids
     * @return
     */
    @ApiOperation(value = "删除",notes = "删除")
    @PostMapping("/delete")
    public MyResult delete(@RequestBody List<Long> ids){
        if(ids.size() > 0){
            SysColumn sysColumn = sysColumnService.getById(ids.get(0));
            if(sysColumn != null){
                SysBuildings sysBuildings = sysBuildingsService.getById(sysColumn.getBuildingsId());
                sysBuildings.setSumColumnNumber(ids.size());
                sysBuildingsService.updateById(sysBuildings);
            }
            sysColumnService.removeByIds(ids);
        }
        return MyResult.success();
    }
}
